<template>
  <el-form style="margin: 20px;width: 350px;" label-position="top">
    <el-form-item :label="$t('loginform.keyManagerAddress')">
      <el-input v-model="form.keyManagerAddress" :placeholder="$t('loginform.placeholder')" style="max-width: 600px">
        <template #append>
          <el-button :disabled="isScanning" @click="search">{{ isScanning ? $t('loginform.scanning') : $t('loginform.autoScan') }}</el-button>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item label="">
      <div v-for="(result, index) in scanResult" :key="index" class="search-result">
        <el-tag @click="selectResult(result)">
          {{ result }}
        </el-tag>
      </div>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import ApiClient from '../api/ApiClient';

export default defineComponent({
  name: 'KeyManagerForm',
  setup() {
    const form = reactive({ keyManagerAddress: 'ws://192.168.2.54:13301/ws' });
    const scanResult = ref<string[]>([]);
    const isScanning = ref(false);
    const { t } = useI18n();

    const initForm = () => {
      const savedKeyManagerAddress = localStorage.getItem('keyManagerAddress');
      if (savedKeyManagerAddress) {
        scanResult.value = JSON.parse(savedKeyManagerAddress);
      }
    };

    const search = () => {
      isScanning.value = true; // 设置按钮为禁用状态并显示“扫描中”
      scanResult.value = [];
      localStorage.setItem('keyManagerAddress', JSON.stringify(scanResult.value));
      ApiClient.scanServer(addResult)
        .then(() => {
          ElMessage.success(t('loginform.scanSuccess'));
        })
        .catch(() => {
          ElMessage.error(t('loginform.scanFailure'));
        })
        .finally(() => {
          isScanning.value = false; // 恢复按钮状态
        });
    };

    const addResult = (result: string) => {
      console.log(result);
      scanResult.value.push(result);
      localStorage.setItem('keyManagerAddress', JSON.stringify(scanResult.value));
    };

    const selectResult = (result: string) => {
      form.keyManagerAddress = result;
    };

    onMounted(() => {
      initForm();
    });

    return {
      form,
      scanResult,
      isScanning,
      search,
      selectResult,
      t
    };
  },
});
</script>

<style scoped>
.search-result {
  margin-bottom: 8px;
}

.login-dialog {
  width: 500px !important;
}
</style>